% function basically for converting the data format used in
% batchTrackVasodilationVesselFill_v2_2 into a format that stores the
% tracking from a single experiment together

function groupLoopedTrackingData_v2_0
warning('off','all')

RE = '_Metadata_';
fn = dir(['*',RE,'*.mat']);
alltifs = dir('*.tif');

individualselections = false;       %this is a sentinal variable that defaults to false. but if you're just selecting one vessel in a FOV to track and you're NOT copying the selections across repeats then this switches to true and you'll default average kymographs

for n = 1:length(fn)
    try
    load(fn(n).name,'ballTrackingData','stimparams','preStimTime','postStimTime','movindicator','rectPositions')
    catch
        disp(['unable to properly load ',fn(n).name,'...moving on...'])
        continue;
    end
    ind = strfind(fn(n).name,RE);
    if isempty(ind)
        continue;
    end
    
    rt = fn(n).name(1:(ind-1));
    %remove dashes and underscores etc that can vary 
    exp = '[^ \f\n\r\t\v.,;:_-]*';
    repeatnumber = regexp(fn(n).name(ind:end),'\d*','Match');
    rt = regexp(rt,exp,'match'); rt = [rt{:}]; 
    rt2 = [rt,repeatnumber{1}];
    fn2 = [];
    count = 0;
    for n2 = 1:length(alltifs)
        temp = regexp(alltifs(n2).name,exp,'match');temp = [temp{:}];
        if contains(temp,rt2)
            count = count + 1;
            fn2{count} = alltifs(n2).name;
        end
    end    
    
    r = [];
    
    for n2 = 1:length(fn2)          %this SHOULD correctly order the movies
        cur = strrep(fn2{n2},'.tif','_tracerTracking_preselected2.mat');
        if ~isfile(cur)
            cur = strrep(fn2{n2},'.tif','_InterptracerTracking_preselected2.mat');
            if ~isfile(cur)
                continue;
            end
        end
        load(cur)
        if isempty(results.kymos)
            clear results
            continue;
        end
        
        if isempty(r)
            r = results;
            r.validtracking = validtracking;
            r.movname = convertCharsToStrings(r.movname);
            firstMovName = r.movname;
        else
            if size(r.rawTracking,1) == size(results.rawTracking,1)
                r.rawTracking = cat(3,r.rawTracking,results.rawTracking);
                r.edgepos = [r.edgepos;results.edgepos];
                r.kymos = [r.kymos;results.kymos];
                r.roughedges = [r.roughedges;results.roughedges];
                r.movname = [r.movname,convertCharsToStrings(results.movname)];
                r.validtracking = [r.validtracking;validtracking];
                r.individualSelections = false;
            else
                r.rawTracking = nancat2(r.rawTracking,results.rawTracking,3);

                temp1 = r.edgepos;
                temp2 = results.edgepos;
                temp3 = max(size(temp1),size(temp2));
                temp3 = cell(temp3(1)+1,temp3(2));
                temp3(end,1:size(temp2,2)) = temp2;
                temp3(1:(size(temp3,1)-1),1:size(temp1,2)) = temp1;
                r.edgepos = temp3;
                
                temp1 = r.kymos;
                temp2 = results.kymos;
                temp3 = max(size(temp1),size(temp2));
                temp3 = cell(temp3(1)+1,temp3(2));
                temp3(end,1:size(temp2,2)) = temp2;
                temp3(1:(size(temp3,1)-1),1:size(temp1,2)) = temp1;
                r.kymos = temp3;
                
                temp1 = r.roughedges;
                temp2 = results.roughedges;
                temp3 = max(size(temp1),size(temp2));
                temp3 = cell(temp3(1)+1,temp3(2));
                temp3(end,1:size(temp2,2)) = temp2;
                temp3(1:(size(temp3,1)-1),1:size(temp1,2)) = temp1;
                r.roughedges = temp3;
                
                r.movname = [r.movname,convertCharsToStrings(results.movname)];
                r.validtracking = nancat(r.validtracking,validtracking,1);
                r.individualSelections = true;
            end
        end
        
        clear validtracking
    end
    if isempty(r)
        continue;
    end
    r.preStimTime = preStimTime;
    r.postStimTime = postStimTime;
    r.stimparams = stimparams;
    [stiminfo,uniqueID,~,stimID] = getStimInfo_v4_4(firstMovName,fn(n).name,r);
    r.stimID = stimID';
    r.ballTracking = [];
    for n2 = 1:length(ballTrackingData)
        numframes = size(r(1).rawTracking,2);
        cur = ballTrackingData{n2};
        cur = cur(1:(length(cur)-1));
        cur = diff(cur);
        t =linspace(1,numframes,numel(cur));
        cur = interp1(t,cur,1:numframes,'nearest');
        r.ballTracking = [r.ballTracking;cur];
    end
    results = r;
    savename = [rt,'-',repeatnumber{1},'_groupedResults.mat'];
    save(savename,'results');
    clear r results
end
        
warning('on','all')

        
    